﻿#region Disclaimer / License
// Copyright (C) 2011, Kenneth Bergeron, IAP Worldwide Services, Inc
// NOAA :: National Marine Fisheries Service
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataSets
{
    /// <summary>
    /// Some global space for the support database
    /// </summary>
    public abstract class Glob
    {
        /// <summary>
        /// The name of this thing
        /// </summary>
        public static string PackageName = "CatchProcessing";
        /// <summary>
        /// The global support database
        /// </summary>
        public static EASASettingsDataSet Support = new EASASettingsDataSet();
        /// <summary>
        /// Where we started
        /// </summary>
        public static string ApplicationStartupFolder 
        { 
            get 
            { 
                return System.IO.Path.GetDirectoryName(
                    System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); 
            }
        }
        /// <summary>
        /// Load the local database from XML
        /// </summary>
        /// <param name="aPackageName">Name of the thing</param>
        /// <returns>null if OK, else exception thrown</returns>
        public static Exception[] LoadSupport(string aPackageName, string aApplicationDataFolder)
        {
            List<Exception> Result = new List<Exception>();
            if (!string.IsNullOrEmpty(aApplicationDataFolder))
            {
                Exception Exc = TestAppDataFolder(aApplicationDataFolder);
                if (Exc != null) Result.Add(Exc);
                else ApplicationDataFolder = aApplicationDataFolder;
            }
            PackageName = aPackageName;
            Support.Load();
            if (Support.VesselCodes.Count == 0) 
                Result.Add( new Exception("Nothing loaded: "+EASASettingsDataSet.DefaultXMLFile) );
            return Result.ToArray();
        }
        /// <summary>
        /// Where the EASA (SDES, SDESCP, ...) database is (hard coded)
        /// </summary>
        public const string EASADataFolder = @"C:\EASA_Database";
        /// <summary>
        /// The name of the EASA database file
        /// </summary>
        public static string EASADatabase = string.Empty;
        /// <summary>
        /// Locate the template SDES Access mdb file
        /// </summary>
        /// <remarks>
        /// Looks for the template in the default data directory; if found, returns the latest version;
        /// if not there, looks for SDESCP.mdb in the application directory.  
        /// </remarks>
        /// <param name="aVesselCode">Vessel ID</param>
        /// <param name="aCruise">Cruise number</param>
        /// <returns>Template database</returns>
        public static string GetDatabase(string aVesselCode, string aCruise)
        {
            // Look for the database in the EASA dir
            string[] DatabaseFiles = System.IO.Directory.GetFiles(EASADataFolder, "CR" + aVesselCode + aCruise + "*.mdb");
            // If there is no installed template, use the one that comes with the application
            if (DatabaseFiles == null || DatabaseFiles.Length == 0)
                return string.Empty;
            // Get the latest version (in the off case that there are more than one)
            Array.Sort(DatabaseFiles);
            // Propably, one day, gonna need some version logic here...
            return DatabaseFiles[DatabaseFiles.Length - 1];
        }
        public static string GetEASATemplate()
        {
            string Name = System.IO.Path.Combine(
                System.IO.Path.GetDirectoryName(EASADatabase),
                "Template" + System.IO.Path.GetFileName(EASADatabase));
            if (!System.IO.File.Exists(Name))
            {
                System.IO.File.Copy(EASADatabase, Name);
                System.IO.File.SetAttributes(Name, System.IO.FileAttributes.ReadOnly);
            }
            return Name;
        }
        /// <summary>
        /// The appliation common data folder, defaults to system common
        /// </summary>
        public static string ApplicationDataFolder =
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
        /// <summary>
        /// Makes a full path to the application data directory
        /// </summary>
        /// <param name="aFile">File name (will strip existing path)</param>
        /// <returns>File name with full path to application directory</returns>
        public static string DefaultFilePath(string aFile)
        {
            return System.IO.Path.Combine(ApplicationDataFolder, System.IO.Path.GetFileName(aFile));
        }
        /// <summary>
        /// Get vessel and cruise from installed daatabase files
        /// </summary>
        /// <param name="outVesselCode">Vessel Code</param>
        /// <param name="outCruise">Cruise Number</param>
        /// <returns>atabse name or null of none</returns>
        public static string GetVesselCruise(out string outVesselCode, out string outCruise)
        {
            outVesselCode = outCruise = string.Empty;
            if (!System.IO.Directory.Exists(EASADataFolder)) return string.Empty;
            foreach (string F in System.IO.Directory.GetFiles(EASADataFolder, "CR*.mdb").Where(qS=>!qS.Contains("Posted")))
            {
                string fn = System.IO.Path.GetFileName(F);
                System.Text.RegularExpressions.Match M = System.Text.RegularExpressions.Regex.Match(
                    fn, @"^CR(\d\d)(\d\d\d\d)");
                if (M.Success)
                {
                    outVesselCode = M.Groups[1].Value;
                    outCruise = M.Groups[2].Value;
                    return F;
                }
            }
            return string.Empty;

        }
        /// <summary>
        /// Fill the SDES Access tables
        /// </summary>
        public static void LoadSDES(string aFile, EASADataSet aDataSet)
        {
            Properties.Settings.Default.SetEASADatabase(aFile);
            new EASADataSetTableAdapters.catchTableAdapter().Fill(aDataSet._catch);
            new EASADataSetTableAdapters.tagnumbersTableAdapter().Fill(aDataSet.tagnumbers);
            new EASADataSetTableAdapters.stationsTableAdapter().Fill(aDataSet.stations);
            new EASADataSetTableAdapters.samplesTableAdapter().Fill(aDataSet.samples);
            new EASADataSetTableAdapters.lengthfreqTableAdapter().Fill(aDataSet.lengthfreq);
            new EASADataSetTableAdapters.lengthdetailsTableAdapter().Fill(aDataSet.lengthdetails);
            new EASADataSetTableAdapters.eventsTableAdapter().Fill(aDataSet.events);
        }
        private static EASADataSet LocalEASADataSet = null;
        public static EASADataSet theEASADataSet
        {
            get
            {
                if (LocalEASADataSet == null)
                {
                    LocalEASADataSet = new EASADataSet();
                    Properties.Settings.Default.SetEASADatabase(EASADatabase);
                    new EASADataSetTableAdapters.longlineTableAdapter().Fill(LocalEASADataSet.longline);
                    new EASADataSetTableAdapters.eventsTableAdapter().Fill(LocalEASADataSet.events);
                    new EASADataSetTableAdapters.stationsTableAdapter().Fill(LocalEASADataSet.stations);
                }
                return LocalEASADataSet;
            }
        }
        /// <summary>
        /// Check a folder for fitness to become my common app data folder
        /// </summary>
        /// <param name="aFolder">Folder to test</param>
        /// <returns>null if OK, otherwise Exception</returns>
        public static Exception TestAppDataFolder(string aFolder)
        {
            Exception Result = null;
            // Does it exist?
            if (!System.IO.Directory.Exists(aFolder)) return new Exception("Directory " + aFolder + " not found");
            // OK, it exists and seems OK, try creating a file in it.
            string TestFile = System.IO.Path.Combine(aFolder, "Test.txt");
            try
            {
                System.IO.File.AppendAllText(TestFile, "This is a test");
                System.IO.File.Delete(TestFile);
            }
            catch (Exception Ex)
            {
                Result = new Exception("Could not create, write or delete in " + aFolder, Ex);
            }
            return Result;
        }
    }
}
